jQuery(document).ready(function() {
}).click (function (e)
{
    e = e || window.event;
    if (e.target.className != "ever_c" && e.target.className != "img"  )

    {
      $('.color_change').removeClass('open');
    }
     if (e.target.className != "edit")

    {
      $('.r_content .question-box').each(function(index, el) {
        var new_text=$(this).find('textarea').val();
         $(this).find('i').text(new_text);
         $(this).find('textarea').remove();
        
      });
    }
});








    window.onload = function() {
  function loading_show(){
    $('.load_box').remove();
   var loading_html='<div class="load_box"><span><img src="http://ai.ilikemanga.com/Public/images/loading.gif"></span></div>';
   $('body').append(loading_html);
    }
    function loading_hide(){
        $('.load_box').remove()
    }

/*jQuery.ajax({
    url: "http://ai.ilikemanga.com/index.php?s=/Home/Comic/ajax_getchapter",
    type: 'post',
    dataType: 'json',
    data:'',
    success: function (rs) {
      console.log(rs)
    }
});*/






  function line(id){
      /*左侧坐标*/
      var last_arr=[];
      var all_arr={};
     
    $('.confirming_box').each(function(index, el) {
        var objsL=[];
        var page_id=$(this).find('input[name="page_id"]').val();
       $(this).find('.confirm_L .question-box').each(function () {
          var _id=$(this).attr('data-num');
          var obj_ever ={};
          var _top = $(this).css('top');
          var _left = $(this).css('left');
          var _width = $(this).css('width');
          var _height = $(this).css('height'); 
           _top=parseInt(_top);
          _left=parseInt(_left)
          _width=parseInt(_width)
          _height=parseInt(_height)
           obj_ever['merge_id']=_id;
           obj_ever['ltop']=_top;
           obj_ever['lleft']=_left;
           obj_ever['lwidth']=_width;
           obj_ever['lheight']=_height;
           obj_ever['cn_text']=$(".c_text[data-num='"+_id+"']").find('textarea').val();
            var r_obj=$(".r_content .question-box[data-num='"+_id+"']");
           obj_ever['en_text']=r_obj.find('i').text();

           obj_ever['rtop']=parseInt(r_obj.css('top'));
           obj_ever['rleft']=parseInt(r_obj.css('left'));
           obj_ever['rwidth']=parseInt(r_obj.css('width'));
           obj_ever['rheight']=parseInt(r_obj.css('height'));
           obj_ever['chapter_no']=$('input[name="chapter_no"]').val();
          objsL.push(obj_ever);
     
      });
      all_arr['page_id']=page_id;
      all_arr['data']=objsL;
       last_arr.push(all_arr);



  

       
    });
    console.log(last_arr)

  }


line()




/*size修改*/
$('.size').change(function(event) {
  var this_val=$(this).val();
  $(this).parents('.confirm_R').find('.question-box.active').css('font-size',this_val+'px');
  $(this).parents('.confirm_R').find('.question-box').removeClass('active');
});


/*色卡显示以及选择*/
$('.color_change').click(function(event) {
  if($(this).hasClass('open')){
    $(this).removeClass('open');
  }else{
    $(this).addClass('open')
  }
});
$('.color_box span').click(function(event) {
  var _color=$(this).css('background');
  $(this).parents('.confirm_R').find('.color_change i').css('background',_color);
   $(this).parents('.confirm_R').find('.question-box.active').css('color',_color);
   $(this).parents('.confirm_R').find('.question-box').removeClass('active');
});

/*行间距设置*/

$('.line_change').change(function(event) {
  var this_val=$(this).val();
  $(this).parents('.confirm_R').find('.question-box.active').css('line-height',this_val);
  $(this).parents('.confirm_R').find('.question-box').removeClass('active');
});








/*适应高度*/
function auto_h(cur,type){
   var w=cur.width();
   if(type=='textarea'){
    var _text=cur.find('textarea').val();
   }else{
    var _text=cur.find('i').text();
   }
  var size=cur.css('font-size');
  $('#ss').css({
    'font-size': size,
    'width':w
  });
  $('#ss').text(_text);
  cur.css('height',$('#ss').height())
  }

$('.r_content .question-box').each(function(index, el) {
  var cur=$(this);
     auto_h(cur)
 
});
/*右侧textarea*/


/*$(document).keydown(function (event) {
    alert(event.keyCode);
});*/
jQuery('body').on('keydown',".r_content textarea",function(){
  var cur=$(this).parents('.question-box');
  auto_h(cur,'textarea')

});







function operation(cur,type){
  loading_show();
  /*type resizes:拖拽+drags：移动     add:新增        del:删除*/
  var _id=cur.attr('data-num')
  var obj_ever ={};
  var _top =cur.css('top');
  var _left = cur.css('left');
  var _width =cur.css('width');
  var _height = cur.css('height'); 
  _top=parseInt(_top);
  _left=parseInt(_left)
  _width=parseInt(_width)
  _height=parseInt(_height)
   obj_ever['page_id']=cur.parents('.confirming_box').find('input[name="page_id"]').val();
   obj_ever['merge_id']=_id;
   obj_ever['type']=type;
   obj_ever['ltop']=_top;
   obj_ever['lleft']=_left;
   obj_ever['lwidth']=_width;
   obj_ever['lheight']=_height;
  console.log(obj_ever)
  //var rs={"code":0,"message":"success","data":{"cn_text":"\u6211\u662f\u4e2d\u56fd\u4eba","en_text":"I am Chinese","page_id":"7.18.jpg","merge_id":"1"}}


    if(type=="resizes"|| type=="drags"){
     /* 拖拽+移动*/
      jQuery.ajax({
          url: "http://ai.ilikemanga.com/index.php?s=/Home/Comic/ajax_adjrect",
          type: 'post',
          dataType: 'json',
          data: obj_ever,
          success: function (rs) {
            loading_hide();
           if(rs.code==0){
            cur.parents('.confirming_box').find(".r_content img").attr('src',rs.data.bg_picurl)
            cur.parents('.confirming_box').find(".confirm_C").find(".c_text[data-num='"+_id+"']").find('textarea').val(rs.data.merge_stext);
            cur.parents('.confirming_box').find(".r_content").find(".question-box[data-num='"+_id+"']").find('i').text(rs.data.merge_ttext);
            cur.parents('.confirming_box').find(".r_content").find(".question-box[data-num='"+_id+"']").css({
              'left': rs.data.rx+'px',
              'top':rs.data.ry+'px',
              'width':rs.data.rwidth,
              'height':rs.data.rheight
            });
            auto_h(cur.parents('.confirming_box').find(".r_content").find(".question-box[data-num='"+_id+"']"),type)    
            }
          }
      });

    }else if(type=="add"){
      /*新增*/

       
       
       jQuery.ajax({
          url: "http://ai.ilikemanga.com/index.php?s=/Home/Comic/ajax_newrect",
          type: 'post',
          dataType: 'json',
          data: obj_ever,
          success: function (rs) {
        if(rs.code==0){
          loading_hide();
          var merge_id=rs.data.merge_id;
          cur.find('.merge_id').text(merge_id);
       cur.attr('data-num',merge_id);
          cur.parents('.confirming_box').find('.confirm_C').append('<div class="c_text" data-num="'+merge_id+'"><textarea>'+rs.data.merge_stext+'</textarea><span class="merge_id">'+merge_id+'</span></div>');
          cur.parents('.confirming_box').find('.r_content').append('<div class="question-box question-border" data-num="'+merge_id+'" style="width:0px;height:0px;left:0px;top:0px;"><i>'+rs.data.merge_ttext+'</i><span class="merge_id">'+merge_id+'</span></div>');   
            cur.parents('.confirming_box').find(".r_content img").attr('src',rs.data.bg_picurl);
            cur.parents('.confirming_box').find(".r_content").find(".question-box[data-num='"+merge_id+"']").css({
              'left': rs.data.rx+'px',
              'top':rs.data.ry+'px',
              'width':rs.data.rwidth,
              'height':rs.data.rheight
            });
      $('.question-box').resizable({ handles: 'n, e, s, w,se'}).draggable();
            }
          }
      });

    }else{
      /*删除*/

      jQuery.ajax({
          url: "http://ai.ilikemanga.com/index.php?s=/Home/Comic/ajax_delrect",
          type: 'post',
          dataType: 'json',
          data: obj_ever,
          success: function (rs) {
              if(rs.code==0){
                loading_hide()
                cur.parents('.confirming_box').find(".r_content img").attr('src',rs.data.bg_picurl)
                cur.parents('.cutting').find('.c_text').each(function(index, el) {
                  if($(this).attr('data-num')==_id){
                    $(this).remove();
                  }
                });
               cur.parents('.cutting').find('.r_content .question-box').each(function(index, el) {
                if($(this).attr('data-num')==_id){
                  $(this).remove();
                }
              });
              cur.remove();
              }


          }
      });

       
    }

 
}




      $('.question-box').resizable({ handles: 'n, e, s, w,se'}).draggable();
      $('body').on('resizestop','.confirm_L .question-box', function(event, ui) {
        var cur=ui.helper;
        operation(cur,'resizes');
     });
      $( "body" ).on( "dragstop",'.confirm_L .question-box' ,function( event, ui ) {
         var cur=ui.helper;
         operation(cur,'drags');
      } );

      var key_db=0;
      jQuery('body').on('click',".question-box",function(){
        if(key_db==0){
          if($(this).hasClass('active')){
            $(this).removeClass('active')
          }else{
             $(this).addClass('active')
          }
        }
        
      });
       jQuery('body').on('dblclick',".r_content .question-box",function(){
        $(this).removeClass('active')
        key_db=1;
        var _text=$(this).find('i').text();
        $(this).find('i').text('');
        $(this).append('<textarea class="edit">'+_text+'</textarea>');
      });




      function stopDefault(e) {
        if(e && e.preventDefault)
          e.preventDefault();
        else
          window.event.returnValue = false;
        return false;
      }

      function oBox() {
        var wId = "w";
        var index = 0;
        var target = null;
        var startX = 0, startY = 0;
        var flag = false;
        var startL = 0, startT = 0, boxHeight = 0, boxWidth = 0;
        var boxObj = $('.confirmingAppraisal');
       



        var newMarkPos = {
          "left": startL,////按下时鼠标距离的左边的距离
          "top": startT////按下时鼠标距离的上边的距离
        }
        //鼠标点击

       boxObj.mousedown(function(e){
         var frame = $(this)
        var referenceSize = {
          "pos": frame.offset(),
          "width": frame.outerWidth(),
          "height": frame.outerHeight()
        }




          flag = true;
          var e = window.event || e;
          target = e.target || e.srcElement; //获取document 对象的引用
          //e.pageY，e.pageX兼容
         
          if(target.src) {
            stopDefault(e)
          }
          var scrollTop = $(document).scrollTop();
          var scrollLeft =$(document).scrollLeft();
          var ePageX = e.clientX + scrollLeft;
          var ePageY = e.clientY + scrollTop;
          //按下时鼠标距离页面的距离
          startX = ePageX;
          startY = ePageY;

          //按下时鼠标距离的左边和上边的距离
          startL = startX - referenceSize.pos.left;
          startT = startY - referenceSize.pos.top;
          index++;
          // 如果鼠标在 box 上被按下
          if(target.className.match(/del-box/i)) {
            // 允许拖动
            flag = false;
            // 设置当前 box 的 id 为 moving_box
            var movingBox = document.getElementById("moving_box")
            if(movingBox !== null) {
              movingBox.removeAttribute("id");
            }
            target.id = "moving_box";
            removeBox(target);
          } else {
          if(target.className.indexOf('ui-resizable-handle')>-1 || target.className.indexOf('question-box')>-1    ){
      
             flag = false;

          }else{
             var div = document.createElement("div");
            div.id = wId + index;
            div.className = "dashed-box";
            $(this).append(div);
            div = null;
          }
          }
        });
        //鼠标离开

        $('.confirmingAppraisal').mouseup(function(e){
    
          var e = window.event || e;
          if(boxWidth >= 1 || boxHeight >= 1) {

             $('#'+wId + index).remove();
            index++;
            var div = document.createElement("div");
            var spanObj = document.createElement("span");
            spanObj.className = 'del-box';
            div.appendChild(spanObj);
            div.className = "question-box question-border";
            div.style.left = newMarkPos.left + "px";
            div.style.top = newMarkPos.top + "px";
            div.style.width = boxWidth + "px";
            div.style.height = boxHeight + "px";
            var id_arr=[];
            $(this).find('.question-box').each(function(index, el) {
              id_arr.push($(this).attr('data-num')); 
            });
            /*最大的id值*/
            var max_id=Math.max.apply(null, id_arr);
            max_id=max_id+1;
            $(this).append(div);
            div = null;
            boxWidth = 0;
            boxHeight = 0;
             $(this).find('.question-box').last().append('<span class="merge_id"></span>')
    
             $('.question-box').resizable({ handles: 'n, e, s, w,se'}).draggable();
            var cur=$(this).find('.question-box').last();
             operation(cur,'add')
          } else {
            if(flag) {
                   $('#'+wId + index).remove();
             

            }
          }
          flag = false;
        });
        //鼠标移动

        boxObj.mousemove(function(e){
    
          var e = window.event || e;
          stopDefault(e)
          if(flag) {
            var scrollTop =$(document).scrollTop();
            var scrollLeft =$(document).scrollLeft();
            var ePX = e.clientX + scrollLeft;
            var ePY = e.clientY + scrollTop;



            var disW = ePX - startX;
            var disH = ePY - startY;
            var L = startL + disW;
            var T = startT + disH;
            if(disW > 0) {
              if(L >= 0) {
                boxWidth = disW
              }
              newMarkPos.left = startL;
            } else {
              if(L <= 0) {
                L = 0;
                boxWidth = startL;
              }
              boxWidth = (startL - L);
              newMarkPos.left = L;
            }
            if(disH > 0) {
              if(T >= 0) {
                boxHeight = disH
              }
              newMarkPos.top = startT;
            } else {
              if(T <= 0) {
                T = 0;
                boxHeight = startT;
              }
              boxHeight = (startT - T)
              newMarkPos.top = T;
            }

            var out_top=$(document).scrollTop(); 
            var red_w=newMarkPos.top;
            $('#'+wId + index).css({'left':newMarkPos.left,'top':red_w,'width':Math.abs(boxWidth),'height':Math.abs(boxHeight)})
            stopDefault(e)
          }
        });


        var dragBox = function(id) {
          return document.getElementById(id);
        }
      };
      oBox();
      /*删除红色框*/
      function removeBox(obj) {
        if(obj) {
          if($(obj).hasClass('del-box')){
             var this_id=$(obj).parents('.question-box').attr('data-num')
             var cur=$(obj).parents('.question-box');
             operation(cur,'del');
          }
        }
      };



          //var rs={"code":0,"message":"success","data":{"cn_text":"\u6211\u662f\u4e2d\u56fd\u4eba","en_text":"I am Chinese","page_id":"7.18.jpg","merge_id":"1"}}
          jQuery('body').on('change',".c_text",function(){
                    var cur=$(this);
                    var cn_text=$(this).find('textarea').val();
                    console.log(cn_text);
                    var merge_id=$(this).attr('data-num');
                    var page_id =$(this).parents('.confirming_box').find('input[name="page_id"]').val();
                    loading_show();
          
                jQuery.ajax({
                url: "http://ai.ilikemanga.com/index.php?s=/Home/Comic/ajax_translate",
                type: 'post',
                dataType: 'json',
                data: {'cn_text': cn_text, 'merge_id': merge_id,'page_id': page_id},
                success: function (rs) {
                     var merge_id=rs.data.merge_id;
                     var merge_ttext=rs.data.merge_ttext;
                    if(rs.code==0){
                      loading_hide()
                      cur.parents('.cutting').find(".confirm_R .question-box").each(function(index, el) {
                        if($(this).attr('data-num')==merge_id){
                          $(this).find('i').text(merge_ttext)
                          auto_h($(this),'type')   
                        }
                      });
                    }
                }
            });
                    
          })









    }
